<template>
	<div class="split-pane-wrapper">
		<div class="mian" ref="boxPage">
			<div class="pane left" :style="{ width: changeWidth ,paddingRight:`${triggerWidth/2}px`}">
				<slot name="left">left</slot>
			</div>
			<div
				class="string"
				:style="{ left: stringLocation, width: `${triggerWidth}px` }"
				@mousedown="lineDown"
			></div>
			<div class="pane right" :style="{ left: changeWidth, paddingLeft:`${triggerWidth/2}px`}">
				<slot name="right">right</slot>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			isUplift: true, //记录鼠标是否抬起
		};
	},
	props: {
		/**
		 * @description 竖线的偏移量
		 */
		leftOffset: {
			type: Number,
			default: 0.3,
		},
		/**
		 * @description 中间竖线的宽度
		 */
		triggerWidth: {
			type: Number,
			default: 10,
		},
		/**
		 * @description 可滑动的最小值
		 */
		min: {
			type: Number,
			default: 0.1,
		},
		/**
		 * @description 可滑动的最大值
		 */
		max: {
			type: Number,
			default: 0.9,
		},
	},
	computed: {
		/**
		 * @description 左右区域相对变化
		 */
		changeWidth() {
			return `${this.leftOffset * 100}%`;
		},
		/**
		 * @description 让左右两边各覆盖这个竖线50%
		 * @attention 运算符前后一定要加空格
		 */
		stringLocation() {
			return `calc(${this.leftOffset * 100}% - ${this.triggerWidth / 2}px)`;
		},
	},
	watch: {
	},
	mounted() {},
	methods: {
		/**
		 * @description 当数遍按下时给DOM绑定鼠标移动事件
		 */
		lineDown(event) {
			this.isUplift = false;
			document.addEventListener("mousemove", this.lineMove);
			document.addEventListener("mouseup", this.lineUplift);
			/**
			 * @description 去掉鼠标在竖线里面的距离并定义到this身上
			 */
			this.initOffset =
				event.pageX - event.srcElement.getBoundingClientRect().left;
		},
		/**
		 * @description 通过竖线移动改变左右区域的大小
		 */
		lineMove(event) {
			if (!this.isUplift) {
				const offset = this.$refs.boxPage.getBoundingClientRect();
				/**
				 * @description 鼠标在元素内移动距离左边距的距离
				 */
				let distance =
					(event.pageX - this.initOffset + this.triggerWidth / 2 - offset.left)/offset.width;
				/**
				 * @description 鼠标在元素内移动距离左边距的距离所占元素宽度的比例
				 */
				if (distance < this.min) distance = this.min;
				if (distance > this.max) distance = this.max;
				this.$emit('update:leftOffset', distance);
			}
		},
		lineUplift() {
			this.isUplift = true;
		},
	},
};
</script>

<style lang="less" scoped>
.mian {
	width: 450px;
	height: 250px;
	position: relative;
	display: flex;
	color: #fff;
	.pane {
		position: absolute;
		top: 0;
		height: 100%;
	}
	.left {
		width: 30%;
		background-color: rgb(255, 187, 0);
		user-select: none;
	}
	.right {
		left: 30%;
		right: 0;
		bottom: 0;
		background-color: rgb(116, 20, 155);
		user-select: none;
	}
	.string {
		height: 100%;
		background-color: #666;
		position: absolute;
		top: 0;
		z-index: 3;
		user-select: none;
		cursor: col-resize;
	}
}
</style>